//
//  SEToast.m
//  SleepingElf
//
//  Created by karong on 2023/7/4.
//

#import "SEToast.h"
#import "AFNetworking.h"

@implementation SEToast
NSTimer * _timer;
NSTimer * _simpleTimer;
NSTimer * _loadingTimer;
NSString *_lastVCName;

+ (void)failureWithContent:(NSString *)content {
    [self dismiss];
    AFNetworkReachabilityStatus status = [AFNetworkReachabilityManager sharedManager].networkReachabilityStatus;
    if (status == AFNetworkReachabilityStatusNotReachable) {
        [self simple:@"No network"];
    }
    else if (!SEIsNullOrEmpty(content)) {
        [self simple:content];
    }
    else {
        [self simple:@"Losing contact with data"];
    }
}

+ (void)dismiss {
    [self clearToast];
}

+ (UIView *)sharedView {
    static dispatch_once_t once;
    static UIView *sharedView;
    dispatch_once(&once, ^{
        sharedView = [[UIView alloc] init];
        sharedView.backgroundColor = UIColor.clearColor;
    });
    return sharedView;
}

+ (UIView *)simpleView {
    static dispatch_once_t once;
    static UIView *simpleView;
    dispatch_once(&once, ^{
        simpleView = [[UIView alloc] init];
        simpleView.backgroundColor = [UIColor colorFromHexRGB:@"000000" alpha:0.7];
        simpleView.layer.cornerRadius = 8;
        simpleView.layer.shadowColor = [UIColor colorFromHexRGB:@"000000" alpha:0.7].CGColor;
        simpleView.layer.zPosition = 10000;
    });
    return simpleView;
}

#pragma mark - simple
// 单词文字
+ (void)simple:(NSString *)info {
    if (SEIsNullOrEmpty(info)) {
        return;
    }
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:info];
    [self simpleAttributed:text];
}

+ (void)simpleAttributed:(NSMutableAttributedString *)info {
    info.color = UIColor.whiteColor;
    info.font = [UIFont systemFontOfSize:14];
    [self dismiss];
    [_simpleTimer invalidate];
    _simpleTimer = nil;
    [[self.simpleView viewWithTag:30004] removeFromSuperview];
    
    UILabel *label = [[UILabel alloc]init];
    label.textColor = UIColor.clearColor;
    label.numberOfLines = 0;
    label.tag = 30004;
    label.textAlignment = NSTextAlignmentCenter;
    label.attributedText = info;
    
    // 完全控制:
    YYTextLinePositionSimpleModifier *modifier = [YYTextLinePositionSimpleModifier new];
    modifier.fixedLineHeight = 24;
    YYTextContainer *container = [YYTextContainer new];
    container.size = CGSizeMake(kScreenWidth - 32, CGFLOAT_MAX);
    container.linePositionModifier = modifier;
    YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:info];
    CGSize size = layout.textBoundingSize;
    
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    
    [self.simpleView addSubview:label];
    [window addSubview:self.simpleView];
    
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.width.height.mas_equalTo(self.simpleView);
    }];
    
    CGFloat width = size.width + 24;
    if(width > kScreenWidth - 24) {
        width = kScreenWidth - 24;
    }
    
    bool hasKeyboard = NO;
    NSString *className = NSStringFromClass([UIViewController currentViewController].class);
//    if ([className isEqualToString:@"WSReadTagKeyAVC"]) {
//        hasKeyboard = YES;
//    }
    
    [self.simpleView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(window).offset(hasKeyboard ? -(kScreenHeight/2) : -96);
        make.centerX.mas_equalTo(window);
        make.width.mas_equalTo(width);
        make.height.mas_equalTo(size.height + 16);
    }];
    
    [self.simpleView layoutIfNeeded];
    [UIView animateWithDuration:0.2 animations:^{
        self.simpleView.alpha = 1;
        [self.simpleView layoutIfNeeded];
    }];
    
    _simpleTimer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(clearSimpleToast) userInfo:nil repeats:NO];
}

#pragma mark - Loading
+ (void)loading {
    // 记录当前需要弹出的VC
    _lastVCName = NSStringFromClass([UIViewController currentViewController].class);
    [_timer invalidate];
    _timer = nil;
    [_loadingTimer invalidate];
    _loadingTimer = nil;
    [[self.sharedView viewWithTag:30004] removeFromSuperview];
    [[self.sharedView viewWithTag:30005] removeFromSuperview];
    [[self.sharedView viewWithTag:30007] removeFromSuperview];
    
    _loadingTimer = [NSTimer scheduledTimerWithTimeInterval:0.8 target:self selector:@selector(showDefaulLoadingView) userInfo:nil repeats:NO];
}

+ (void)showDefaulLoadingView {
    UIViewController *controller = [self currentViewController];
    if (!controller || !controller.view) {
        return;
    }
    [controller.view addSubview:self.sharedView];
    [self.sharedView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(controller.view);
        make.width.mas_equalTo(115.5);
        make.height.mas_equalTo(115.5);
    }];
    [self showLoadingView:controller];
}

+ (void)loadingIntegralWall {
    // 记录当前需要弹出的VC
    _lastVCName = NSStringFromClass([UIViewController currentViewController].class);
    [_timer invalidate];
    _timer = nil;
    [_loadingTimer invalidate];
    _loadingTimer = nil;
    [[self.sharedView viewWithTag:30004] removeFromSuperview];
    [[self.sharedView viewWithTag:30005] removeFromSuperview];
    [[self.sharedView viewWithTag:30006] removeFromSuperview];
    [[self.sharedView viewWithTag:30007] removeFromSuperview];
    [self showFullLoadingViewCanClose:YES];
}

+ (void)loadingFull {
    // 记录当前需要弹出的VC
    _lastVCName = NSStringFromClass([UIViewController currentViewController].class);
    [_timer invalidate];
    _timer = nil;
    [_loadingTimer invalidate];
    _loadingTimer = nil;
    [[self.sharedView viewWithTag:30004] removeFromSuperview];
    [[self.sharedView viewWithTag:30005] removeFromSuperview];
    [[self.sharedView viewWithTag:30006] removeFromSuperview];
    [[self.sharedView viewWithTag:30007] removeFromSuperview];
    [self showFullLoadingViewCanClose:NO];
}

+ (void)showFullLoadingViewCanClose:(BOOL)can {
    UIViewController *controller = [self currentViewController];
    if (!controller || !controller.view) {
        return;
    }
    [controller.view addSubview:self.sharedView];
    [self.sharedView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(controller.view);
        make.width.mas_equalTo(kScreenWidth);
        make.height.mas_equalTo(kScreenHeight);
    }];
    [self showLoadingView:controller];
    if (can) {
        UIButton *closeBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        closeBtn.tag = 30007;
        [closeBtn setTitle:@"CLOSE" forState:(UIControlStateNormal)];
        closeBtn.titleLabel.font = [UIFont systemFontOfSize:14 weight:UIFontWeightMedium];
        [closeBtn setTitleColor:UIColor.whiteColor forState:(UIControlStateNormal)];
        [closeBtn addTarget:self action:@selector(closeAction:) forControlEvents:(UIControlEventTouchUpInside)];
        closeBtn.layer.cornerRadius = 14;
        closeBtn.layer.borderColor = UIColor.whiteColor.CGColor;
        closeBtn.layer.borderWidth = 1;
        closeBtn.hidden = YES;
        [self.sharedView addSubview:closeBtn];
        [closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.sharedView).offset(-8);
            if (SEIsiPhoneX) {
                make.top.mas_equalTo(self.sharedView).offset(100);
            }
            else {
                make.top.mas_equalTo(self.sharedView).offset(74);
            }
            make.width.offset(66);
            make.height.offset(28);
        }];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            closeBtn.hidden = NO;
        });
    }
}

+ (void)closeAction:(UIButton *)sender {
    [self dismiss];
}

+ (void)showLoadingView:(UIViewController *)controller {
    UIImageView * image = [[UIImageView alloc]initWithImage:SEIMG(@"loading")];
    image.frame = CGRectMake(100, 100, 60, 60);
    image.tag = 30005;
    [self.sharedView addSubview:image];
    [image mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(self.sharedView);
    }];
    CABasicAnimation *rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    rotationAnimation.duration = 1;
    rotationAnimation.cumulative = YES;
    rotationAnimation.repeatCount = 10000;
    [image.layer addAnimation:rotationAnimation forKey:@"rotationAnimation"];
    // 如果已经切换了页面loadin不再弹出
    if (![_lastVCName isEqualToString:NSStringFromClass(controller.class)]) {
        [self dismiss];
    }
    else {
        [self.sharedView layoutIfNeeded];
        [UIView animateWithDuration:0.2 animations:^{
            self.sharedView.alpha = 1;
            [self.sharedView layoutIfNeeded];
        }];
    }
}

#pragma mark - 清除Toast

+ (void)clearToast {
    [_loadingTimer invalidate];
    _loadingTimer = nil;
    [_timer invalidate];
    _timer = nil;
    [UIView animateWithDuration:0.2 animations:^{
        [self sharedView].alpha = 0;
        [self.sharedView layoutIfNeeded];
    } completion:^(BOOL finished) {
        if(finished) {
            [[self sharedView] removeFromSuperview];
        }
    }];
}

+ (void)clearSimpleToast {
    [_simpleTimer invalidate];
    _simpleTimer = nil;
    [UIView animateWithDuration:0.2 animations:^{
        self.simpleView.alpha = 0;
        [self.simpleView layoutIfNeeded];
    } completion:^(BOOL finished) {
        if(finished) {
            [self.simpleView removeFromSuperview];
        }
    }];
}

#pragma mark - 获取视图

// 获取当前视图
+ (UIViewController *)currentViewController {
    UIViewController *resultVC;
    resultVC = [self _topViewController:[[UIApplication sharedApplication].keyWindow rootViewController]];
    while (resultVC.presentedViewController) {
        resultVC = [self _topViewController:resultVC.presentedViewController];
    }
    return resultVC;
}

+ (UIViewController *)_topViewController:(UIViewController *)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self _topViewController:[(UINavigationController *)vc topViewController]];
    } else if ([vc isKindOfClass:[UITabBarController class]]) {
        return [self _topViewController:[(UITabBarController *)vc selectedViewController]];
    } else {
        return vc;
    }
    return nil;
}
@end
